import os
import sys
import platform
import subprocess
import shutil
from setuptools import setup, Extension
from setuptools.command.build_ext import build_ext
from setuptools.command.install import install

# 读取版本号
def get_version():
    version_path = os.path.join(os.path.dirname(__file__), "VERSION")
    if os.path.exists(version_path):
        with open(version_path, "r") as f:
            return f.read().strip()
    return "0.1.0"

# CMake构建扩展命令
class CMakeBuildExt(build_ext):
    def run(self):
        # 确保CMake可用
        try:
            subprocess.check_output(['cmake', '--version'])
        except OSError:
            raise RuntimeError("CMake must be installed to build the following extensions: " +
                               ", ".join(e.name for e in self.extensions))
        
        for ext in self.extensions:
            self.build_extension(ext)

    def build_extension(self, ext):
        extdir = os.path.abspath(os.path.dirname(self.get_ext_fullpath(ext.name)))
        cmake_args = [
            f"-DCMAKE_LIBRARY_OUTPUT_DIRECTORY={extdir}",
            f"-DPYTHON_EXECUTABLE={sys.executable}",
            "-DCMAKE_BUILD_TYPE=Release"
        ]

        # 平台特定配置
        if platform.system() == "Windows":
            cmake_args += ['-G', 'MinGW Makefiles'] if "GCC" in sys.version else ['-A', 'x64']
            cmake_args += ['-DCMAKE_LIBRARY_OUTPUT_DIRECTORY_RELEASE={}'.format(extdir)]
        elif platform.system() == "Darwin":
            cmake_args += ['-DCMAKE_OSX_DEPLOYMENT_TARGET=10.14']

        # 构建目录
        build_temp = os.path.join(self.build_temp, ext.name)
        if not os.path.exists(build_temp):
            os.makedirs(build_temp)
        
        # 配置
        subprocess.check_call(['cmake', os.path.abspath(ext.sourcedir)] + cmake_args, cwd=build_temp)
        
        # 构建
        build_args = ['--config', 'Release']
        if platform.system() == "Windows":
            build_args += ['--', '/m']  # 多核构建
        else:
            build_args += ['--', '-j4']  # 多核构建
        
        subprocess.check_call(['cmake', '--build', '.'] + build_args, cwd=build_temp)
        
        # 复制生成的文件
        if platform.system() == "Windows":
            shutil.copy(os.path.join(build_temp, 'Release', ext.name + '.pyd'), extdir)
        else:
            shutil.copy(os.path.join(build_temp, ext.name + '.so'), extdir)

# 自定义安装命令（可选）
class CustomInstall(install):
    def run(self):
        super().run()
        # 安装完成后可以执行额外操作
        print("Installation completed successfully!")

# 主设置函数
setup(
    name="tinyndarray",
    version=get_version(),
    author="Your Name",
    author_email="your.email@example.com",
    description="A lightweight n-dimensional array implementation",
    long_description=open("README.md", "r", encoding="utf-8").read(),
    long_description_content_type="text/markdown",
    url="https://github.com/yourusername/tinyndarray",
    packages=['tinyndarray'],
    package_dir={'tinyndarray': 'python/tinyndarray'},
    ext_modules=[
        Extension(
            name='tinyndarray._core',
            sources=[],  # 源文件由CMake管理
            language='c++',
            sourcedir='.'  # 项目根目录
        )
    ],
    cmdclass={
        'build_ext': CMakeBuildExt,
        'install': CustomInstall
    },
    install_requires=[
        "numpy",
    ],
    extras_require={
        "test": ["pytest>=6.0"]
    },
    classifiers=[
        "Development Status :: 3 - Alpha",
        "Intended Audience :: Developers",
        "Intended Audience :: Science/Research",
        "License :: OSI Approved :: MIT License",
        "Programming Language :: Python :: 3",
        "Programming Language :: Python :: 3.7",
        "Programming Language :: Python :: 3.8",
        "Programming Language :: Python :: 3.9",
        "Programming Language :: Python :: 3.10",
        "Programming Language :: Python :: 3.11",
        "Programming Language :: C++",
        "Operating System :: POSIX :: Linux",
        "Operating System :: MacOS :: MacOS X",
        "Operating System :: Microsoft :: Windows",
        "Topic :: Scientific/Engineering",
        "Topic :: Software Development :: Libraries"
    ],
    python_requires=">=3.7",
    license="MIT",
    keywords="ndarray array tensor numerical numpy",
    zip_safe=False,
)